//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 杨雨哲 on 15/6/25.
//  Copyright © 2015年 yyz. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    // 定义常量
    
    private let WB_Client_ID = "4035796988"
    private let WB_Redirect_URI = "http://www.baidu.com"
    private let WB_App_Secret = "89fad8ff2e18b891e5c203a9d4d71a0c"
    
    lazy var webView :UIWebView? = {
        let v = UIWebView()
        v.delegate = self
        return v
    }()
    
    override func loadView() {
        
        view = webView
        
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOAuthPage()
    }
    
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private func loadOAuthPage(){
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        let url = NSURL(string: urlString)!
        
        webView?.loadRequest(NSURLRequest(URL: url))
    
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        
        if !urlString.hasPrefix(WB_Redirect_URI){
            return true
        }
        
        let query = request.URL!.query!
        let codeStr = "code="
        
        if query.hasPrefix(codeStr){
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            
            loadAccessToken(code)
        }
        else{
            
            close()
        }
        
        return false
    }
    
    private func loadAccessToken(code:String){
        let urlString = "oauth2/access_token"
        
        let params = ["client_id":WB_Client_ID,
            "client_secret":WB_App_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_Redirect_URI]
        

            NetworkTool.sharedNetworkTool().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            // 字典转模型 －> 加载用户信息，链式调用 Alamofire
                UserAccount(dict: JSON as! [String : AnyObject]).loadUserInfo { (account, error) -> () in
                
                // 判断账户信息是否正确
                    if account != nil {
                    print(account)
                    // 1. 设置全局的 account
                    sharedUserAccount = account
                        print(sharedUserAccount)
                    
                    // 2. 发送通知
                    // object = false 表示显示 WelcomeViewController
                    NSNotificationCenter.defaultCenter().postNotificationName(YZSwitchRootVCNotification, object: false)
                    
                    // 强烈不建议写！
                    // UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
                    
                    // 3. 关闭当前控制器
                    self.close()
                    
                    return
                }
                
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }

        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("拼命加载中~")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

}
